package net.xinqushi.gc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 混合Bean回收结论：
 *  MixBean被回收时，内部的引用(Person)会被一起回收。
 *  但是MixBean使用单例时(包含了static类型变量)，此时不会回收的，因为无法回收static方法区的内容
 *  静态变量：
 *  静态变量(StrongReference)在类被卸载的时候才会被销毁，而类只有在进程结束的时候才会被卸载，
 *  也就是说被static修饰的静态变量只有在进程被销毁的时候才会被回收
 * @see ReferenceDemo
 */
public class MixBeanGC {

    public static void main(String[] args) {
        MixBean mixBean = new MixBean();
        //MixBean mixBean = MixBean.getInstance();
        //mixBean =null;
        while(true){
            System.gc();
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("gc");
        }
    }

    static class MixBean{
        private static MixBean single;
        static ReentrantLock singleLock = new ReentrantLock();
        public static MixBean getInstance(){
            try {
                singleLock.lock();
                if(single == null){
                    return single = new MixBean();
                }
                return single;
            }finally {
                singleLock.unlock();
            }

        }
        String mixName = "mixName";
        Person person = new Person();

        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println(this.getClass() + " is finalized");
        }
    }

    public static class Person{
        public int age = 20;
        @Override
        protected void finalize() throws Throwable {
            super.finalize();
            System.out.println(this.getClass() + " is finalized");
        }
    }
}
